package lc20240628;

import java.util.List;
import java.util.HashSet;
import java.util.Set;

//单词拆分
public class WordBreak {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordSet = new HashSet<>(wordDict);  // 将 wordDict 转换为一个集合，以便于快速查找
        boolean[] dp = new boolean[s.length() + 1];    // dp[i] 表示 s 的前 i 个字符是否可以拼接成
        dp[0] = true;   // 初始化空字符串
        
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && wordSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        
        return dp[s.length()];
    }

    public static void main(String[] args) {
        WordBreak wb = new WordBreak();
        List<String> wordDict = List.of("apple", "pen");
        String s = "applepenapple";
        System.out.println("Can the string be segmented? " + wb.wordBreak(s, wordDict));  // true

        wordDict = List.of("cats", "dog", "sand", "and", "cat");
        s = "catsandog";
        System.out.println("Can the string be segmented? " + wb.wordBreak(s, wordDict));  // false
    }
}
